using System;
using System.Windows;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.SmartParts;
using Microsoft.Practices.CompositeUI.WPF;
using Microsoft.Practices.ObjectBuilder;

using Jbe.TestSuite.Infrastructure.Interface;
using System.Windows.Threading;
using System.Windows.Controls;
using Jbe.TestSuite.Infrastructure.Interface.Services;

namespace Jbe.TestSuite.TestDevice.SignalVisualizer.Views
{
    /// <summary>
    /// Interaction logic for VisualizerView.xaml
    /// </summary>
    public partial class VisualizerView : UserControl, IVisualizerView, IDisposable
    {
        private delegate void AddSampleDelegate(object device, double amplitude, double relativeTime);

        private IEditManager editManager;

        [ServiceDependency]
        public IEditManager EditManager
        {
            set
            {
                editManager = value;
                editManager.Register(scaleX);
                editManager.Register(scaleY);
            }
        }

        /// <summary>
        /// Initialize a new instance of <see cref="VisualizerView"/>.
        /// <summary>
        public VisualizerView()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(OnLoad);
        }

        /// <summary>
        /// Called when WPF has loaded the control and is ready to display it.
        /// <summary>
        /// <param name="sender">Source of the event</param>
        /// <param name="e">Extra information about the event</param>
        public void OnLoad(object sender, RoutedEventArgs e)
        {
            _presenter.OnViewReady();
        }

        public void AddSample(object device, double amplitude, double relativeTime)
        {
            if (Dispatcher.CheckAccess())
            {
                InnerAddSample(device, amplitude, relativeTime);
            }
            else
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new AddSampleDelegate(InnerAddSample), device, amplitude, relativeTime);
            }
        }

        private void InnerAddSample(object device, double amplitude, double relativeTime)
        {
            signalView.AddSample(device, relativeTime, amplitude);
        }

        // This method is invoked during disposing of the control.
        private void ResetClick(object sender, RoutedEventArgs e)
        {
            signalView.ScaleX = 1;
            signalView.ScaleY = 1;
        }

        private void EditHandlerDeregister()
        {
            editManager.Deregister(scaleX);
            editManager.Deregister(scaleY);
        }
    }
}
